package com.jwaoo.chat.session.input;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.dx.as.common.ILoadListener;
import com.dx.as.common.log.LogUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.config.Config;
import com.dx.as.upload.UploadFile;
import com.jwaoo.audio.AudioRecorder;
import com.jwaoo.audio.IAudioRecordCallback;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.R;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.session.actions.BaseAction;
import com.jwaoo.chat.session.actions.Container;
import com.jwaoo.chat.session.emoji.EmoticonPickerView;
import com.jwaoo.chat.session.emoji.IEmoticonSelectedListener;
import com.jwaoo.chat.session.emoji.MoonUtil;
import com.jwaoo.media.dialog.EasyAlertDialogHelper;
import com.jwaoo.media.video.helper.RequestCode;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 底部文本编辑，语音等模块
 * Created by hzxuwen on 2015/6/16.
 */
public class InputPanel implements IEmoticonSelectedListener, IAudioRecordCallback {

    private static final String TAG = "MsgSendLayout";
    private static final int SHOW_LAYOUT_DELAY = 200;
    protected Container container;
    protected Handler uiHandler;
    protected View actionPanelBottomLayout; // 更多布局
    protected View audioPanelLayout; // 语音布局
    protected LinearLayout messageActivityBottomLayout;
    protected EditText messageEditText;// 文本消息编辑框
    protected FrameLayout textAudioSwitchLayout; // 切换文本，语音按钮布局
    protected View switchToTextButtonInInputBar;// 文本消息选择按钮
    protected View switchToSnapButtonInInputBar;
    protected View switchToAudioButtonInInputBar;// 语音消息选择按钮
    protected View moreFuntionButtonInInputBar;// 更多消息选择按钮
    protected View sendMessageButtonInInputBar;// 发送消息按钮
    protected View emojiButtonInInputBar;// 发送消息按钮
    protected View messageInputBar;
    protected ImageView audioRecordBtn;
    protected boolean isSnap = false;
    // 表情
    protected EmoticonPickerView emoticonPickerView;  // 贴图表情控件

    // 语音
    protected AudioRecorder audioMessageHelper;
    private TextView time;
    private boolean started = false;
    private boolean cancelled = false;
    private boolean touched = false; // 是否按着
    private boolean isKeyboardShowed = true; // 是否显示键盘

    // state
    private boolean actionPanelBottomLayoutHasSetup = false;
    private boolean isTextAudioSwitchShow = true;

    // adapter
    private List<BaseAction> actions;

    // data
    private long typingTime = 0;

    // message edit watcher

    private MessageEditWatcher watcher;

    public InputPanel(Container container,List<BaseAction> actions, boolean isTextAudioSwitchShow) {
        this.container = container;
        this.actions = actions;
        this.uiHandler = new Handler();
        this.isTextAudioSwitchShow = isTextAudioSwitchShow;
        init();
    }

    public InputPanel(Container container, List<BaseAction> actions) {
        this(container, actions, true);
    }

    public void onPause() {
        // 停止录音
        if (audioMessageHelper != null) {
            onEndAudioRecord(true);
        }
    }

    public void onDestroy() {
        // release
        if (audioMessageHelper != null) {
            audioMessageHelper.onDestory();
            audioMessageHelper = null;
        }
        uiHandler = null;
    }

    public boolean collapse(boolean immediately) {
        boolean respond = (emoticonPickerView != null && emoticonPickerView.getVisibility() == View.VISIBLE
                || actionPanelBottomLayout != null && actionPanelBottomLayout.getVisibility() == View.VISIBLE);

        hideAllInputLayout(immediately);

        return respond;
    }

    public void setWatcher(MessageEditWatcher watcher) {
        this.watcher = watcher;
    }

    private void init() {
        initViews();
        initInputBarListener();
        initTextEdit();
        initAudioRecordButton();
        restoreText(false);

        for (int i = 0; i < actions.size(); ++i) {
            actions.get(i).setIndex(i);
            actions.get(i).setContainer(container);
        }
    }

    private void initViews() {
        // input bar
        messageActivityBottomLayout = (LinearLayout) container.activity.findViewById(R.id.messageActivityBottomLayout);
        messageInputBar = container.activity.findViewById(R.id.textMessageLayout);
        switchToTextButtonInInputBar = container.activity.findViewById(R.id.buttonTextMessage);
        switchToSnapButtonInInputBar = container.activity.findViewById(R.id.buttonSnapMessage);
        switchToAudioButtonInInputBar = container.activity.findViewById(R.id.buttonAudioMessage);
        moreFuntionButtonInInputBar = container.activity.findViewById(R.id.buttonMoreFuntionInText);
        emojiButtonInInputBar = container.activity.findViewById(R.id.emoji_button);
        sendMessageButtonInInputBar = container.activity.findViewById(R.id.buttonSendMessage);
        messageEditText = container.activity.findViewById(R.id.editTextMessage);
        audioPanelLayout = container.activity.findViewById(R.id.audio_record_view);

        // 语音
        audioRecordBtn = (ImageView) container.activity.findViewById(R.id.img_audio);
        time = (TextView) container.activity.findViewById(R.id.tv_audio_time);

        // 表情
        emoticonPickerView = (EmoticonPickerView) container.activity.findViewById(R.id.emoticon_picker_view);

        // 显示录音按钮
        switchToTextButtonInInputBar.setVisibility(View.GONE);
        switchToSnapButtonInInputBar.setVisibility(View.GONE);
        switchToAudioButtonInInputBar.setVisibility(View.VISIBLE);

        // 文本录音按钮切换布局
        textAudioSwitchLayout = (FrameLayout) container.activity.findViewById(R.id.switchLayout);
        if (isTextAudioSwitchShow) {
            textAudioSwitchLayout.setVisibility(View.VISIBLE);
        } else {
            textAudioSwitchLayout.setVisibility(View.GONE);
        }
    }

    private void initInputBarListener() {
        switchToTextButtonInInputBar.setOnClickListener(clickListener);
        switchToSnapButtonInInputBar.setOnClickListener(clickListener);
        switchToAudioButtonInInputBar.setOnClickListener(clickListener);
        emojiButtonInInputBar.setOnClickListener(clickListener);
        sendMessageButtonInInputBar.setOnClickListener(clickListener);
        moreFuntionButtonInInputBar.setOnClickListener(clickListener);
    }

    private void initTextEdit() {
        messageEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        messageEditText.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN && !isSnap) {
                    switchToTextLayout(true);
                }
                return false;
            }
        });

        messageEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                messageEditText.setHint("");
                checkSendButtonEnable(messageEditText);
            }
        });

        messageEditText.addTextChangedListener(new TextWatcher() {
            private int start;
            private int count;

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                this.start = start;
                this.count = count;
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkSendButtonEnable(messageEditText);
                MoonUtil.replaceEmoticons(container.activity, s, start, count);

                if (watcher != null) {
                    watcher.afterTextChanged(s, start, count);
                }

                int editEnd = messageEditText.getSelectionEnd();
                messageEditText.removeTextChangedListener(this);
                while (StringUtil.counterChars(s.toString()) > 5000 && editEnd > 0) {
                    s.delete(editEnd - 1, editEnd);
                    editEnd--;
                }
                messageEditText.setSelection(editEnd);
                messageEditText.addTextChangedListener(this);

                sendTypingCommand();
            }
        });
    }


    /**
     * 发送“正在输入”通知
     */
    private void sendTypingCommand() {

        if (System.currentTimeMillis() - typingTime > 5000L) {
            typingTime = System.currentTimeMillis();
        }
    }

    /**
     * ************************* 键盘布局切换 *******************************
     */

    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == switchToTextButtonInInputBar) {
                switchToTextLayout(true);// 显示文本发送的布局
            } else if (v == sendMessageButtonInInputBar) {
                onTextMessageSendButtonPressed();
            } else if (v == switchToAudioButtonInInputBar) {
                switchToAudioLayout();
            } else if (v == moreFuntionButtonInInputBar) {
                if (isSnap){
                    hideSnapView();
                }else {
                    toggleActionPanelLayout();
                }
            } else if (v == emojiButtonInInputBar) {
                toggleEmojiLayout();
            } else if (v == audioPanelLayout){
                toggleAudioPanelLayout();
            } else if (v == switchToSnapButtonInInputBar) {
                container.proxy.showCameraSelector();
            }
        }
    };

    public void hideMuneLayout(){
        hideEmojiLayout();
        hideAudioPanelLayout();
        hideActionPanelLayout();
    }


    public void showSnapView(){
        hideActionPanelLayout();
        switchToSnapButtonInInputBar.setVisibility(View.VISIBLE);
        switchToAudioButtonInInputBar.setVisibility(View.GONE);
        switchToTextButtonInInputBar.setVisibility(View.GONE);

        emojiButtonInInputBar.setBackgroundResource(R.drawable.fire_emoji_switch_btn);
        moreFuntionButtonInInputBar.setBackgroundResource(R.drawable.fire_cancel_switch_btn);
        isSnap = true;
    }

    public void hideSnapView(){
        emojiButtonInInputBar.setBackgroundResource(R.drawable.dialogue_emoji_switch_btn);
        moreFuntionButtonInInputBar.setBackgroundResource(R.drawable.dialogue_more_switch_btn);

        switchToSnapButtonInInputBar.setVisibility(View.GONE);
        switchToAudioButtonInInputBar.setVisibility(View.VISIBLE);
        switchToTextButtonInInputBar.setVisibility(View.GONE);
        isSnap = false;
    }


    // 点击edittext，切换键盘和更多布局
    private void switchToTextLayout(boolean needShowInput) {
        hideEmojiLayout();
        hideActionPanelLayout();
        audioPanelLayout.setVisibility(View.GONE);
        messageEditText.setVisibility(View.VISIBLE);
        switchToTextButtonInInputBar.setVisibility(View.GONE);
        switchToAudioButtonInInputBar.setVisibility(View.VISIBLE);
        switchToSnapButtonInInputBar.setVisibility(View.GONE);
        messageInputBar.setVisibility(View.VISIBLE);

        if (needShowInput) {
            uiHandler.postDelayed(showTextRunnable, SHOW_LAYOUT_DELAY);
        } else {
            hideInputMethod();
        }
    }

    // 发送文本消息
    private void onTextMessageSendButtonPressed() {
        String text = messageEditText.getText().toString();
        int size = Config.text_max_length;
        int number = text.length()/size;

        String value;
        for (int i = 0; i <= number; i ++){
            if (number == i){
                value = text.substring(i*Config.text_max_length);
            }else {
                value = text.substring(i*size, (i+1)*size);
            }
            Message textMessage = MessageHandler.getInstace(container.activity).createMessage(ChatConstants.text,container.account ,value);
            textMessage.setSnap(isSnap ? ChatConstants.snap : ChatConstants.unsnap);
            textMessage.setIsRead(isSnap ? ChatConstants.unRead : ChatConstants.isRead);
            if (container.proxy.sendMessage(textMessage)) {
                MessageHandler.getInstace(container.activity.getApplicationContext()).sendMessage(textMessage);
            }
        }
        restoreText(true);

    }

    // 切换成音频，收起键盘，按钮切换成键盘
    private void switchToAudioLayout() {
        messageEditText.setVisibility(View.GONE);
        audioPanelLayout.setVisibility(View.VISIBLE);
        hideInputMethod();
        hideEmojiLayout();
        hideActionPanelLayout();

        switchToAudioButtonInInputBar.setVisibility(View.GONE);
        switchToTextButtonInInputBar.setVisibility(View.VISIBLE);
        switchToSnapButtonInInputBar.setVisibility(View.GONE);
    }



    // 点击“+”号按钮，切换更多布局和键盘
    private void toggleActionPanelLayout() {

        if (actionPanelBottomLayout == null || actionPanelBottomLayout.getVisibility() == View.GONE) {
            showActionPanelLayout();

        } else {
            hideActionPanelLayout();
        }
    }

    private void toggleAudioPanelLayout(){
        if (audioPanelLayout == null || audioPanelLayout.getVisibility() == View.GONE){
            showAudioPanelLayout();
        }else {
            hideAudioPanelLayout();
        }
    }

    private void showAudioPanelLayout(){
        uiHandler.postDelayed(showAudioRecordRunnable,SHOW_LAYOUT_DELAY);
    }

    private void hideAudioPanelLayout(){
        uiHandler.postDelayed(hideAudioRecordRunnable,SHOW_LAYOUT_DELAY);
    }

    // 点击表情，切换到表情布局
    private void toggleEmojiLayout() {
        if (emoticonPickerView == null || emoticonPickerView.getVisibility() == View.GONE) {
            showEmojiLayout();
        } else {
            hideEmojiLayout();
        }
    }

    // 隐藏表情布局
    private void hideEmojiLayout() {
        if (uiHandler != null){
            uiHandler.removeCallbacks(showEmojiRunnable);
        }
        if (emoticonPickerView != null) {
            emoticonPickerView.setVisibility(View.GONE);
        }
    }

    // 隐藏更多布局
    private void hideActionPanelLayout() {
        uiHandler.removeCallbacks(showMoreFuncRunnable);
        if (actionPanelBottomLayout != null) {
            actionPanelBottomLayout.setVisibility(View.GONE);
        }
    }

    // 隐藏键盘布局
    private void hideInputMethod() {
        isKeyboardShowed = false;
        uiHandler.removeCallbacks(showTextRunnable);
        InputMethodManager imm = (InputMethodManager) container.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(messageEditText.getWindowToken(), 0);
        messageEditText.clearFocus();
    }

    // 隐藏语音布局
    private void hideAudioLayout() {
        audioPanelLayout.setVisibility(View.GONE);
        messageEditText.setVisibility(View.VISIBLE);
        if (isSnap) return;
        switchToTextButtonInInputBar.setVisibility(View.VISIBLE);
        switchToSnapButtonInInputBar.setVisibility(View.GONE);
        switchToAudioButtonInInputBar.setVisibility(View.GONE);
    }

    // 显示表情布局
    private void showEmojiLayout() {
        hideInputMethod();
        hideActionPanelLayout();
        hideAudioLayout();

        messageEditText.requestFocus();
        uiHandler.postDelayed(showEmojiRunnable, 200);
        emoticonPickerView.setVisibility(View.VISIBLE);
        emoticonPickerView.show(this);
        container.proxy.onInputPanelExpand();
    }

    // 初始化更多布局
    private void addActionPanelLayout() {
        if (actionPanelBottomLayout == null) {
            View.inflate(container.activity, R.layout.nim_message_activity_actions_layout, messageActivityBottomLayout);
            actionPanelBottomLayout = container.activity.findViewById(R.id.actionsLayout);
            actionPanelBottomLayoutHasSetup = false;
        }
        initActionPanelLayout();
    }

    // 显示键盘布局
    private void showInputMethod(EditText editTextMessage) {
        editTextMessage.requestFocus();
        //如果已经显示,则继续操作时不需要把光标定位到最后
        if (!isKeyboardShowed) {
            editTextMessage.setSelection(editTextMessage.getText().length());
            isKeyboardShowed = true;
        }

        InputMethodManager imm = (InputMethodManager) container.activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editTextMessage, 0);

        container.proxy.onInputPanelExpand();
    }

    // 显示更多布局
    private void showActionPanelLayout() {
        addActionPanelLayout();
        hideEmojiLayout();
        hideInputMethod();
        hideAudioLayout();

        uiHandler.postDelayed(showMoreFuncRunnable, SHOW_LAYOUT_DELAY);
        container.proxy.onInputPanelExpand();
    }

    // 初始化具体more layout中的项目
    private void initActionPanelLayout() {
        if (actionPanelBottomLayoutHasSetup) {
            return;
        }

        ActionsPanel.init(container.activity, actions);
        actionPanelBottomLayoutHasSetup = true;
    }

    private Runnable showEmojiRunnable = new Runnable() {
        @Override
        public void run() {
            emoticonPickerView.setVisibility(View.VISIBLE);
        }
    };

    private Runnable showMoreFuncRunnable = new Runnable() {
        @Override
        public void run() {
            actionPanelBottomLayout.setVisibility(View.VISIBLE);

        }
    };

    private Runnable showAudioRecordRunnable = new Runnable() {
        @Override
        public void run() {
            actionPanelBottomLayout.setVisibility(View.GONE);
        }
    };

    private Runnable hideAudioRecordRunnable = new Runnable() {
        @Override
        public void run() {
            audioPanelLayout.setVisibility(View.GONE);
        }
    };


    private Runnable showTextRunnable = new Runnable() {
        @Override
        public void run() {
            showInputMethod(messageEditText);
        }
    };

    private void restoreText(boolean clearText) {
        if (clearText) {
            messageEditText.setText("");
        }

        checkSendButtonEnable(messageEditText);
    }

    /**
     * 显示发送或更多
     *
     * @param editText
     */
    private void checkSendButtonEnable(EditText editText) {
        String textMessage = editText.getText().toString();
        if (!TextUtils.isEmpty(StringUtil.removeBlanks(textMessage)) && editText.hasFocus()) {
            moreFuntionButtonInInputBar.setVisibility(View.GONE);
            sendMessageButtonInInputBar.setBackgroundResource( isSnap ? R.drawable.fire_send_btn : R.drawable.dialogue_send_btn);
            sendMessageButtonInInputBar.setVisibility(View.VISIBLE);
        } else {
            sendMessageButtonInInputBar.setVisibility(View.GONE);
            moreFuntionButtonInInputBar.setVisibility(View.VISIBLE);
        }
    }

    /**
     * *************** IEmojiSelectedListener ***************
     */
    @Override
    public void onEmojiSelected(String key) {
        Editable mEditable = messageEditText.getText();
        if (key.equals("/DEL")) {
            messageEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
        } else {
            int start = messageEditText.getSelectionStart();
            int end = messageEditText.getSelectionEnd();
            start = (start < 0 ? 0 : start);
            end = (start < 0 ? 0 : end);
            mEditable.replace(start, end, key);
        }
    }

    private Runnable hideAllInputLayoutRunnable;
    //发送贴图
    @Override
    public void onStickerSelected(String category, String item) {
        Log.i("InputPanel", "onStickerSelected, category =" + category + ", sticker =" + item);
    }

    /**
     * 隐藏所有输入布局
     */
    private void hideAllInputLayout(boolean immediately) {
        if (hideAllInputLayoutRunnable == null) {
            hideAllInputLayoutRunnable = new Runnable() {

                @Override
                public void run() {
                    hideInputMethod();
                    hideActionPanelLayout();
                    hideEmojiLayout();
                }
            };
        }
        long delay = immediately ? 0 : ViewConfiguration.getDoubleTapTimeout();
        uiHandler.postDelayed(hideAllInputLayoutRunnable, delay);
    }


    /**
     * ****************************** 语音 ***********************************
     */
    private void initAudioRecordButton() {
        audioRecordBtn.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    touched = true;
                    Log.e("===","MotionEvent.ACTION_DOWN");
                    initAudioRecord();
                    onStartAudioRecord();
                } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_UP) {
                    Log.e("===","MotionEvent.ACTION_CANCEL || MotionEvent.ACTION_UP");
                    touched = false;
                    onEndAudioRecord(isCancelled(v, event));
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    Log.e("===","MotionEvent.ACTION_MOVE");
                    touched = true;
                    cancelAudioRecord(isCancelled(v, event));
                }

                return false;
            }
        });
    }

    // 上滑取消录音判断
    private static boolean isCancelled(View view, MotionEvent event) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);

        if (event.getRawX() < location[0] || event.getRawX() > location[0] + view.getWidth()
                || event.getRawY() < location[1] - 40) {
            return true;
        }

        return false;
    }

    /**
     * 初始化AudioRecord
     */
    private void initAudioRecord() {
        if (audioMessageHelper == null) {
            audioMessageHelper = AudioRecorder.getAudioRecorder(uiHandler,this);
            audioMessageHelper.initMedia();
        }
    }

    /**
     * 开始语音录制
     */
    private void onStartAudioRecord() {
        container.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        audioMessageHelper.startRecord();
        cancelled = false;
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                time.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 结束语音录制
     *
     * @param cancel
     */
    private void onEndAudioRecord(boolean cancel) {
        started = false;
        container.activity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        audioMessageHelper.completeRecord(cancel);
//        audioRecordBtn.setText(R.string.record_audio);
//        audioRecordBtn.setBackgroundResource(R.drawable.nim_message_input_edittext_box);
        started = false;
        container.activity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        uiHandler.post(new Runnable() {
            @Override
            public void run() {

                time.setText("0");
                time.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    public void onRecording(final long lng) {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                time.setText(lng+"");
            }
        });
    }

    /**
     * 取消语音录制
     *
     * @param cancel
     */
    private void cancelAudioRecord(boolean cancel) {
        // reject
        if (!started) {
            return;
        }
        // no change
        if (cancelled == cancel) {
            return;
        }

        cancelled = cancel;
    }

    // 录音状态回调
    @Override
    public void onRecordReady() {

    }

    @Override
    public void onRecordStart() {
        started = true;
        if (!touched) {
            return;
        }
        LogUtil.d("=====","start Anim");
    }

    @Override
    public void onRecordSuccess(final File audioFile, final long audioLength) {
        FileAttachment fileAttachment = new FileAttachment();
        fileAttachment.setDuration(audioLength);
        fileAttachment.setPath(audioFile.getAbsolutePath());
        //发送语音
        final Message message = MessageHandler.getInstace(container.activity).createMessage(ChatConstants.audio,container.account,fileAttachment);
        container.proxy.sendMessage(message);
        final Map<String,Object> parm = new HashMap<>();
        parm.put("type","audio");
        parm.put("as","pub");
        parm.put("flag","zoom");
        parm.put("end",".amr");
        parm.put("media_type","audio/mpeg");
        UploadFile.uploadFile(parm, audioFile, new ILoadListener() {
            @Override
            public void onResponse(Object response, int flg) {
                if (response != null){
                    Map<String,String> result = (Map<String, String>) response;
                    String url = result.get("path");
                    message.getAttachment().setAttachstate(ChatConstants.transferred);
                    message.getAttachment().setUrl(url);

                    MessageHandler.getInstace(container.activity.getApplicationContext()).sendMessage(message);
                }
            }

            @Override
            public void onFailure(Throwable t) {
                message.getAttachment().setAttachstate(ChatConstants.fail);
                onRecordSuccess(audioFile,audioLength);
            }
        });
    }
    @Override
    public void onRecordFail() {
        if (started) {
            Toast.makeText(container.activity, R.string.recording_error, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRecordCancel() {

    }

    @Override
    public void onRecordReachedMaxTime(final long maxTime) {
        EasyAlertDialogHelper.createOkCancelDiolag(container.activity, "", container.activity.getString(R.string.recording_max_time), false, new EasyAlertDialogHelper.OnDialogActionListener() {
            @Override
            public void doCancelAction() {
                audioMessageHelper.completeRecord(true);
            }

            @Override
            public void doOkAction() {
                audioMessageHelper.handleEndRecord(true, maxTime);
            }
        }).show();
    }


    public boolean hideBottomLayot(){
        if (actionPanelBottomLayout != null && actionPanelBottomLayout.getVisibility() == View.VISIBLE){
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    actionPanelBottomLayout.setVisibility(View.GONE);
                }
            });
            return true;
        }
        return false;
    }



    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        BaseAction action = null;
        switch (requestCode){
            case RequestCode.CAPTURE_VIDEO:
            case RequestCode.GET_LOCAL_VIDEO:
                action = actions.get(5);
                break;
            case RequestCode.PREVIEW_IMAGE_FROM_CAMERA:
            case RequestCode.PICK_IMAGE:
                action = actions.get(4);
                break;
            case RequestCode.PREVIEW_IMAGE_FROM_CAMERA_SNAP:
            case RequestCode.PICK_IMAGE_SNAP:
                action = actions.get(2);
            default:
                break;
        }
        if (action != null) {
            action.onActivityResult(requestCode & 0xff, resultCode, data);
        }
//        int index = (requestCode << 16) >> 24;
//        if (index != 0) {
//            index--;
//            if (index < 0 | index >= actions.size()) {
//                LogUtil.d(TAG, "request code out of actions' range");
//                return;
//            }
//            BaseAction action = actions.get(index);
//            if (action != null) {
//                action.onActivityResult(requestCode & 0xff, resultCode, data);
//            }
//        }
    }


}
